package com.cm.dynamic.classloader.context;

import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;

/**
 * 自定义类加载器上下文
 * @author xionglei
 * @version 1.0.0
 * 2021年08月25日 18:38
 */
public final class ClassLoaderContext {

    private static final ThreadLocal<ClassLoader> currentClassLoader = new NamedThreadLocal<>("Current ClassLoader");


    private ClassLoaderContext() {
    }


    public static ClassLoader currentClassLoader() throws IllegalStateException {
        ClassLoader classLoader = currentClassLoader.get();
        if (classLoader == null) {
            throw new IllegalStateException("Cannot find current ClassLoader: Please setCurrentProxy first");
        }
        return classLoader;
    }

    @Nullable
    public static Object setCurrentProxy(@Nullable ClassLoader classLoader) {
        ClassLoader oldClassLoader = currentClassLoader.get();
        if (classLoader != null) {
            currentClassLoader.set(classLoader);
        } else {
            currentClassLoader.remove();
        }
        return oldClassLoader;
    }

    /**
     * 移除保存的当前线程的类加载器
     * @return
     * @throws IllegalStateException
     */
    public static ClassLoader removeClassLoader() {
        ClassLoader classLoader = currentClassLoader.get();
        if (classLoader != null) {
            currentClassLoader.remove();
        }
        return classLoader;
    }


}
